package io.renren.modules.job.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.utils.RedisKeys;
import io.renren.config.BizConfig;
import io.renren.modules.avanotes.dao.LocalMarkdownNotesDao;
import io.renren.modules.avanotes.entity.LocalMarkdownNotesEntity;
import io.renren.modules.avanotes.service.LocalMarkdownNotesService;
import io.renren.modules.avanotes.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author: xiaomi
 * @date: 2022/1/27
 * @description: 分词任务处理
 */
@Component(BizConfig.TASK_NAME_TOKENIZER)
@Slf4j
public class TokenizerTask implements ITask {

    /**
     * NOTEME 这种定时方式，会造成多线程轮询！但是不知道如何控制单线程？？？
     */
    volatile boolean lock = false;

    @Autowired
    LocalMarkdownNotesService lmdService;

    @Autowired
    LocalMarkdownNotesDao lmdDao;

    @Autowired
    @Qualifier(BizConfig.IMPL_TOKENIZER_INDEX)
    TokenService indexTokenizerService;

    @Override
    public void run(String params) {
        if (lock) {
            log.info("locked,return ...");
            return;
        }
        lock = true;
        try {
            log.info("tokenizer task start!");
            //1.查询所有
            List<LocalMarkdownNotesEntity> list = lmdDao.selectList(new QueryWrapper<LocalMarkdownNotesEntity>().eq(LocalMarkdownNotesEntity.CN_STATUS, LocalMarkdownNotesEntity.STATUS_INIT));
            //2.进行分词处理
            if (CollectionUtils.isEmpty(list)) {
                return;
            }
            for (LocalMarkdownNotesEntity entity : list) {
                String key = RedisKeys.getIndexTokenKey(LocalMarkdownNotesEntity.TABLE_NAME, entity.getId().toString());
                indexTokenizerService.save(key, entity.getContent());
                log.info("添加redis 数据成功！{}", key);
                //更新状态
                lmdDao.updateStatus(entity.getId(), LocalMarkdownNotesEntity.STATUS_COMPLETE);
            }
        } finally {
            //解锁
            lock = false;
        }


    }
}
